<!-- eslint-disable vue/no-parsing-error -->
<template>
  <ebook-dialog :title="title" ref="dialog">
    <div class="dialog-list-wrapper" v-if="!ifNewGroup">
      <div class="dialog-list-item"
           :class="{'is-add': item.edit ? true:false}"
           v-for="(item, index) in categoryList"
           :key="index"
           @click="onGroupClick(item)"
           v-show="(item.edit === 2 && isInGroup) || item.edit !== 2 || !item.edit">
        <div class="dialog-list-item-text">{{item.title}}</div>
        <div class="dialog-list-icon-wrapper" v-if="isInGroup&&shelfCategory.id===item.id">
          <span class="icon-check"></span>
        </div>
      </div>
    </div>
    <div class="dialog-new-group-wrapper" v-else>
      <div class="dialog-input-title-wrapper">
        <span class="dialog-input-title">{{$t('shelf.groupName')}}</span>
      </div>
      <div class="dialog-input-wrapper">
        <div class="dialog-input-inner-wrapper">
          <input type="text" class="dialog-input" v-model="newGroupName" ref="dialogInput">
          <div class="dialog-input-clear-wrapper" @click="clear" v-show="newGroupName&&newGroupName.length > 0">
            <span class="icon-close-circle-fill"></span>
          </div>
        </div>
      </div>
    </div>
    <template v-slot:btn>
      <div class="group-dialog-btn-wrapper">
        <div class="dialog-btn" @click="hide">{{$t('shelf.cancel')}}</div>
        <div class="dialog-btn" @click="createNewGroup" :class="{'is-empty': newGroupName&&newGroupName.length === 0}"
            v-if="ifNewGroup">{{$t('shelf.confirm')}}
        </div>
      </div>
    </template>
  </ebook-dialog>
  <toast :text="toastText" ref="toast"></toast>
</template>

<script>
import EbookDialog from '../common/Dialog.vue'
import Toast from '../common/Toast.vue'
import { storeShelfMixin } from '../../utils/mixin'
import { removeAddFromShelf, appendAddToShelf, computeId } from '../../utils/store'
// eslint-disable-next-line no-unused-vars
import { saveBookShelf, getUsername } from '../../utils/localStorage'
// eslint-disable-next-line no-unused-vars
import { changeShelfGroup } from '@/api/shelf'

export default {
  name: 'group-dialog',
  mixins: [storeShelfMixin],
  components: {
    EbookDialog,
    Toast
  },
  props: {
    showNewGroup: {
      type: Boolean,
      default: false
    },
    groupName: {
      type: String,
      default: ''
    }
  },
  computed: {
    isInGroup () {
      return this.currentType === 2
    },
    defaultCategory () {
      console.log(this.$route.path)
      if (this.$route.path === '/store/category') {
        return [
          {
            title: this.$t('shelf.groupOut'),
            edit: 2
          }
        ]
      } else {
        return [
          {
            title: this.$t('shelf.newGroup'),
            edit: 1
          },
          {
            title: this.$t('shelf.groupOut'),
            edit: 2
          }
        ]
      }
    },
    category () {
      return this.shelfList.filter(item => item.type === 2)
    },
    categoryList () {
      return [...this.defaultCategory, ...this.category]
    },
    title () {
      return !this.ifNewGroup ? this.$t('shelf.moveBook') : this.$t('shelf.newGroup')
    }
  },
  data () {
    return {
      ifNewGroup: false,
      newGroupName: '',
      toastText: ''
    }
  },
  watch: {
    showNewGroup (val) {
      this.ifNewGroup = val
    },
    groupName (val) {
      this.newGroupName = val
    }
  },
  methods: {
    show () {
      this.ifNewGroup = this.showNewGroup
      this.newGroupName = this.groupName
      this.$refs.dialog.show()
    },
    hide () {
      this.$refs.dialog.hide()
      setTimeout(() => {
        this.ifNewGroup = false
      }, 200)
    },
    onGroupClick (item) {
      if (item.edit && item.edit === 1) {
        this.ifNewGroup = true
      } else if (item.edit && item.edit === 2) {
        this.moveOutFromGroup(item)
      } else {
        this.moveToGroup(item)
      }
    },
    clear () {
      this.newGroupName = ''
    },
    moveToGroup (group) {
      const groupName = this.newGroupName === '' ? group.title : this.newGroupName
      changeShelfGroup(groupName, getUsername(), this.shelfSelected).then((res) => {
        if (res.data.status === 0) {
          this.setShelfList(this.shelfList
            .filter(book => {
              if (book.itemList) {
                book.itemList = book.itemList.filter(subBook => this.shelfSelected.indexOf(subBook) < 0)
              }
              return this.shelfSelected.indexOf(book) < 0
            }))
            .then(() => {
              if (group && group.itemList) {
                group.itemList = [...group.itemList, ...this.shelfSelected]
              }
              group.itemList.forEach((item, index) => {
                item.id = index + 1
              })
              this.toastText = this.$t('shelf.moveBookInSuccess').replace('$1', group.title)
              this.$refs.toast.show()
              this.$refs.toast.updateText(this.toastText)
              this.onComplete()
            })
        }
      })
    },
    moveOutFromGroup () {
      changeShelfGroup('0', getUsername(), this.shelfSelected).then((res) => {
        const tlist = this.shelfList.map(book => {
          if (book.type === 2 && book.itemList) {
            book.itemList = book.itemList.filter(subBook => !subBook.selected)
          }
          return book
        })
        const temlist = []
        for (let i = 0; i < tlist.length; i++) {
          if (tlist[i].type === 2 && tlist[i].itemList.length === 0) {
            continue
          }
          temlist.push(tlist[i])
        }
        this.setShelfList(temlist).then(() => {
          const list = computeId(appendAddToShelf([].concat(removeAddFromShelf(this.shelfList), ...this.shelfSelected)))
          this.setShelfList(list).then(() => {
            let f = 0
            for (let i = 0; i < this.shelfList.length; i++) {
              if (this.shelfList[i].title === this.$route.query.title) {
                f = 1
              }
            }
            if (!f) {
              this.$router.push({
                path: '/store/shelf'
              })
            } else {
              this.toastText = this.$t('shelf.moveBookOutSuccess')
              this.$refs.toast.show()
              this.$refs.toast.updateText(this.toastText)
            }
            this.onComplete()
          })
        })
      })
    },
    createNewGroup () {
      if (!this.newGroupName && this.newGroupName.length === 0) {
        return
      }

      if (this.showNewGroup) {
        // 修改分组名
        const curlist = this.shelfList.find(item => item.title === this.$route.query.title)
        changeShelfGroup(this.newGroupName, getUsername(), curlist.itemList).then((res) => {
          if (res.data.status === 0) {
            this.shelfCategory.title = this.newGroupName
            this.onComplete()
          }
        })
      } else {
        // 新建分组
        const group = {
          id: this.shelfList[this.shelfList.length - 2].id + 1,
          itemList: [],
          selected: false,
          title: this.newGroupName,
          type: 2
        }
        let list = removeAddFromShelf(this.shelfList)
        list.push(group)
        list = appendAddToShelf(list)
        console.log(list)
        this.setShelfList(list).then(() => {
          this.moveToGroup(group)
        })
      }
    },
    onComplete () {
      saveBookShelf(this.shelfList)
      this.hide()
      this.setIsEditMode(false)
    }
  }
}
</script>

<style lang="scss" rel="stylesheet/scss" scoped>
  .dialog-list-wrapper {
    width: 100%;
    padding: 0 px2rem(20);
    box-sizing: border-box;
    font-size: px2rem(14);
    @include scroll;
    .dialog-list-item {
      display: flex;
      padding: px2rem(15) 0;
      box-sizing: border-box;
      color: #666;
      &.is-add {
        color: $color-blue;
        &:active {
          color: $color-blue-transparent;
        }
      }
      &:active {
        color: rgba(102, 102, 102, .5)
      }
      .dialog-list-item-text {
        flex: 1;
      }
      .dialog-list-icon-wrapper {
        flex: 0 0 px2rem(30);
        color: $color-blue;
        @include right;
      }
    }
  }

  .dialog-new-group-wrapper {
    width: 100%;
    padding: 0 px2rem(20);
    box-sizing: border-box;
    .dialog-input-title-wrapper {
      font-size: px2rem(10);
      margin-top: px2rem(20);
    }
    .dialog-input-wrapper {
      width: 100%;
      padding: 0 0 px2rem(30) 0;
      box-sizing: border-box;
      .dialog-input-inner-wrapper {
        display: flex;
        width: 100%;
        padding: px2rem(10) 0;
        box-sizing: border-box;
        border-bottom: px2rem(1) solid #eee;
        font-size: px2rem(14);
        color: #666;
        .dialog-input {
          flex: 1;
          border: none;
          &:focus {
            outline: none;
          }
        }
        .dialog-input-clear-wrapper {
          flex: 0 0 px2rem(30);
          color: #ccc;
          @include center;
          &:active {
            color: #999;
          }
        }
      }
    }
  }

  .group-dialog-btn-wrapper {
    width: 100%;
    @include center;
  }
  .dialog-btn {
    flex: 1;
    &.is-empty {
      color: rgba(255, 255, 255, .5);
    }
    &:active {
      color: rgba(255, 255, 255, .5)
    }
  }
</style>
